<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\facade\Jpush;
use app\common\model\Account as AccountModel;
use app\common\model\Assets;
use app\common\model\User;
use app\common\model\VillageFenClear;
use app\common\tool\account\AccountException;
use think\Exception;
use think\facade\Cache;
use think\facade\Event;
use think\facade\Log;

class AccountHandle
{
    public function handle($handle)
    {
        try {
            $time = time();
            $pasture = ['rabbit_coupon', 'ranch_points', 'ranch_bonus'];
            $tillage = ['rabbit_vote', 'rabbit_chain', 'rabbit_baby', 'cloud_points'];
            $village = ['village_bao', 'village_piao', 'village_lian', 'village_fen'];
            if (is_array($handle->account)) {
                if (!is_array($handle->amount) || count($handle->account) != count($handle->amount)) {
                    throw new AccountException('参数account和amount不对应', '0');
                }
                $assets = Assets::where('uid', $handle->uid)->find();
                $bonusTotal = 0;
                foreach ($handle->account as $k => $v) {
                    if ($handle->amount[$k] > 0) {
                        $after = $handle->fx == '+' ? floatval($assets->$v) + floatval($handle->amount[$k]) :
                            floatval($assets->$v) - floatval($handle->amount[$k]);
                        if($after < 0){
                            //throw new AccountException('账户余额不足', '0');break;
                        }
                        $data[] = [
                            'uid' => $handle->uid,
                            'type' => $v,
                            'intro' => $handle->intro,
                            'amount' => $handle->amount[$k],
                            'front' => $assets->$v,
                            'after' => $after,
                            'fx' => $handle->fx,
                            'create_time' => $time,
                            'create_date' => date('Y-m-d'),
                            'source' => $handle->source ?? 0,
                            'msg' => $handle->msg,
                            'is_bonus' => $handle->type == 2 ? 1 : 0,
                            'is_admin' => $handle->type == 3 ? 1 : 0,
                            'is_grant' => $handle->is_grant,
                            'is_user' => $handle->is_user,
                            'category' => $handle->category ?? 0,
                            'is_pasture' => in_array($v, $pasture)? 1 : 0,
                            'is_tillage' => in_array($v, $tillage)? 1 : 0,
                            'is_village' => in_array($v, $village)? 1 : 0,
                        ];
                        $bonusTotal += floatval($handle->amount[$k]);
                        if ($handle->update) {
                            $assets->$v = $after;
                            $assets->save();

                            if($v == 'dedicate'){
                                User::where('id', $handle->uid)->save(['my_dedicate'=>$after]);
                            }
                        }
                    }
                }
                //if ($handle->update) $assets->save();

                if ($handle->category > 0 && $bonusTotal > 0) {
                    Event::trigger('Summary', ['key' => 'sum_' . $handle->category, 'value' => $bonusTotal, 'uid' => $handle->uid]);
                }
            } else {
                $account = $handle->account;
                if ($handle->amount > 0) {
                    $assets = Assets::where('uid', $handle->uid)->find();

                    $after = $handle->fx == '+' ? floatval($assets->$account) + floatval($handle->amount) :
                        floatval($assets->$account) - floatval($handle->amount);
                    if($after < 0){
                        //throw new AccountException($handle->uid.$account.'账户余额不足', '0');
                    }
                    $data[] = [
                        'uid' => $handle->uid,
                        'type' => $account,
                        'intro' => $handle->intro,
                        'amount' => $handle->amount,
                        'front' => $assets->$account,
                        'after' => $after,
                        'fx' => $handle->fx,
                        'create_time' => $time,
                        'create_date' => date('Y-m-d'),
                        'source' => $handle->source ?? 0,
                        'msg' => $handle->msg,
                        'is_bonus' => $handle->type == 2 ? 1 : 0,
                        'is_admin' => $handle->type == 3 ? 1 : 0,
                        'is_grant' => $handle->is_grant,
                        'is_user' => $handle->is_user,
                        'category' => $handle->category ?? 0,
                        'order_id' => $handle->order_id ?? 0,
                        'is_pasture' => in_array($account, $pasture)? 1 : 0,
                        'is_tillage' => in_array($account, $tillage)? 1 : 0,
                        'is_village' => in_array($account, $village)? 1 : 0,
                    ];

                    if ($handle->update) {
                        $assets->$account = $after;
                        $assets->save();
                        if($account == 'dedicate'){
                            User::where('id', $handle->uid)->save(['my_dedicate'=>$after]);
                        }
                    }

                    if ($handle->category > 0) {
                        Event::trigger('Summary', ['key' => 'sum_' . $handle->category, 'value' => $handle->amount, 'uid' => $handle->uid]);
                    }

                    if('village_fen' == $account && !VillageFenClear::where('uid', $handle->uid)->count()){
                        if(isset(Cache::get('system')['village_fen_clear_cycle'])){
                            VillageFenClear::create([
                                'uid' => $handle->uid,
                                'first_time' => $time,
                                'time' => $time,
                                'next_clear_time' => $time + (int)(Cache::get('system')['village_fen_clear_cycle'] * 86400)
                            ]);
                        }
                    }
                }
            }
            if (!empty($data)) {
                (new AccountModel())->insertAll($data);
            }

            if($handle->type == 2){
                $user = User::where('id', $handle->uid)->field('id,registration_id')->find();
                $this->jpush($user);
            }

            return true;

        } catch (\Exception $e) {

            throw new AccountException($e->getMessage(), '0');
        }
    }

    private function jpush($user)
    {
        try{
            $parameter = ['event_type'=>1009,'sub_event_type'=>1104];
            $extra = ['extras'=>['parameter'=>json_encode($parameter)]];
            $alert = '您有一笔收益已到账';
            Jpush::sendSingleNotify($user->registration_id, $alert, $extra, $user->id);
        }catch (Exception $e){
            Log::write("jpush>>".$e->getMessage());
        }

    }
}